package com.wjy.myupdateapp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.wjy.myupdateapp.updater.AppUpdater;
import com.wjy.myupdateapp.updater.bean.DownloadBean;
import com.wjy.myupdateapp.updater.net.INetCallBack;
import com.wjy.myupdateapp.updater.tools.Base64StringTool;
import com.wjy.myupdateapp.updater.ui.UpdateVersionShowDialog;
import com.wjy.myupdateapp.updater.utils.AppUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private String url = "http://59.110.162.30/app_updater_version.json";
    public static final String URL_HOST = "http://36.112.137.125:20204/?s=Platform.Version.GetVersion";
    private Button btn_updater,btn_post,btn_upload,btn_uploadImg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView(){
        btn_updater = findViewById(R.id.btn_updater);
        btn_post = findViewById(R.id.btn_post);
        btn_upload = findViewById(R.id.btn_upload);
        btn_uploadImg = findViewById(R.id.btn_uploadImg);
        btn_updater.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppUpdater.getInstance().getNetManager().get(url, new INetCallBack() {
                    @Override
                    public void success(String response) {
                        Log.e("tag","response="+response);
                        /**
                         * 1.解析json
                         * {
                         *  "title":"4.5.0更新啦！",
                         *  "content":"1. 优化了阅读体验；\n2. 上线了 hyman 的课程；\n3. 修复了一些已知问题。",
                         *  "url":"http://59.110.162.30/v450_imooc_updater.apk",
                         *  "md5":"14480fc08932105d55b9217c6d2fb90b",
                         *  "versionCode":"450"
                         * }
                         * 2.做版本匹配
                         * 如果需要更新
                         * 3.弹窗
                         * 4.点击下载
                         */

                        //1.解析json
                        DownloadBean downloadBean = DownloadBean.parse(response);
                        if (downloadBean == null){
                            Toast.makeText(MainActivity.this,"版本检测接口返回数据异常！",Toast.LENGTH_SHORT).show();
                            return;
                        }

                        //2.检测：是否需要弹窗
                        try {
                            long versinCode = Long.parseLong(downloadBean.versionCode);
                            if (versinCode <= AppUtils.getVersionCode(MainActivity.this)){
                                Toast.makeText(MainActivity.this,"已经是最新版本，无需更新！",Toast.LENGTH_SHORT).show();
                                return;
                            }
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                            Toast.makeText(MainActivity.this,"版本检测接口返回版本号异常！",Toast.LENGTH_SHORT).show();
                            return;
                        }

                        //3.弹窗
                        UpdateVersionShowDialog.show(MainActivity.this,downloadBean);

                        //4.下载
                    }

                    @Override
                    public void failed(Throwable throwable) {
                        throwable.printStackTrace();
                        Toast.makeText(MainActivity.this,"版本更新失败！",Toast.LENGTH_SHORT).show();
                    }
                },MainActivity.this);
            }
        });

        btn_post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RequestBody requestBody = new FormBody.Builder()//创建表单请求体
                        .add("version",String.valueOf(AppUtils.getVersionCode(MainActivity.this)))
                        .build();
                AppUpdater.getInstance().getNetManager().post(URL_HOST, requestBody, new INetCallBack() {
                    @Override
                    public void success(String response) {
                        Log.e("tag","请求成功response="+response);
                    }

                    @Override
                    public void failed(Throwable throwable) {
                        throwable.printStackTrace();
                        Toast.makeText(MainActivity.this,"请求失败！",Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

        final String URL = "https://www.blueerdos.top/erdos_Api/index.php/project/imageFile/upload";
        btn_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String filePath = "/sdcard/UVCCamera/img_goods.png";//文件地址
                File file = new File(filePath);
                Log.e("tag","file.getName()="+file.getName());
                RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"),file);//MediaType.parse("image/*")参考https://www.w3school.com.cn/media/media_mimeref.asp
                RequestBody requestBody = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("file",file.getName(),fileBody)
                        .build();
                AppUpdater.getInstance().getNetManager().upload(URL, requestBody, new INetCallBack() {
                    @Override
                    public void success(String response) {
                        Log.e("tag","response="+response);
                    }

                    @Override
                    public void failed(Throwable throwable) {
                        Log.e("tag","failed");
                    }
                });
            }
        });

        //base64图片上传
        btn_uploadImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String stream = null;
                String filePath = "/sdcard/UVCCamera/img_goods.png";//图片地址
                stream = Base64StringTool.getcomImageBase64(Base64StringTool.getSmallBitmap(filePath));
                if (TextUtils.isEmpty(stream)) {
                    Toast.makeText(MainActivity.this,"图片上传失败！",Toast.LENGTH_SHORT).show();
                    return;
                }

                RequestBody requestBody = new FormBody.Builder()//创建表单请求体
                        .add("file",stream)
                        .build();
                AppUpdater.getInstance().getNetManager().post(URL, requestBody, new INetCallBack() {
                    @Override
                    public void success(String response) {
                        Log.e("tag","请求成功response="+response);
                    }

                    @Override
                    public void failed(Throwable throwable) {
                        throwable.printStackTrace();
                        Toast.makeText(MainActivity.this,"请求失败！",Toast.LENGTH_SHORT).show();
                    }
                });

                requestTest();
                test();
            }
        });
    }

    private void requestTest(){
        String URL = "http://server.fs.nrynr.com/ApiPhoneControls.ashx";
        JSONArray jsonArray = new JSONArray();
        jsonArray.put("admin");
        jsonArray.put("123");

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("Action","LoginOn");
            jsonObject.put("Param",jsonArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e("tag","jsonObject="+jsonObject.toString());
        AppUpdater.getInstance().getNetManager().POST(MainActivity.this,URL, jsonObject.toString(), new INetCallBack() {
            @Override
            public void success(String response) {
                Log.e("tag","请求成功response="+response);
            }

            @Override
            public void failed(Throwable throwable) {
                throwable.printStackTrace();
                Toast.makeText(MainActivity.this,"请求失败！",Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void test(){
        MediaType mediaType = MediaType.parse("text/plain; charset=utf-8");
        String requestBody = "{\"Action\":\"LoginOn\",\"Param\":[\"admin\",\"123\"]}";
        Request request = new Request.Builder()
                .url("http://server.fs.nrynr.com/ApiPhoneControls.ashx")
                .post(RequestBody.create(mediaType, requestBody))
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("test", "onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("test", response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                for (int i = 0; i < headers.size(); i++) {
                    Log.e("test", headers.name(i) + ":" + headers.value(i));
                }
                Log.e("test", "onResponse: " + response.body().string());
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppUpdater.getInstance().getNetManager().cancel(this);
    }
}
